package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.LoginService;
import com.heima.model.admin.dtos.UserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/7/22 19:37
 */

@Service
public class LoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements LoginService {
    @Override
    public ResponseResult login(UserDto userDto) {
        //判断参数：
        if (StringUtils.isBlank(userDto.getName()) || StringUtils.isBlank(userDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据name查询数据库是否存在用户：
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", userDto.getName());
        List<AdUser> list = list(queryWrapper);

        if (list.size() == 0) {
            //用户不存在：
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在！");
        }
        AdUser user = list.get(0);
        //校验密码：
        String password = DigestUtils.md5DigestAsHex((userDto.getPassword() + user.getSalt()).getBytes());

        Map<String, Object> map;
        if (password.equals(user.getPassword())) {
            //登录成功：设置token：
            user.setPassword("");
            user.setSalt("");
            map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
            map.put("user", user);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        return ResponseResult.okResult(map);
    }
}
